package cn.kgc.filter;

import cn.kgc.constant.GateWayConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2022-12-02 11:44
 */
@Component
public class GlobalCachedRequestBodyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest=exchange.getRequest();
        //获得请求的地址
        String uri=serverHttpRequest.getURI().toString();
        //如果是登录请求或者是注册请求，可以将请求直接放行
        boolean isLoginOrRegister=uri.contains(GateWayConstant.LOGIN_URL)||uri.contains(GateWayConstant.REGISTER_URL);
        //如果请求没有参数，请求也可以直接放行
        if (!isLoginOrRegister||serverHttpRequest.getHeaders().getContentType()==null){
            return chain.filter(exchange);
        }
        //其他的请求进行处理：获得原来的请求中的参数的副本，根据副本创建ServerHttpRequest，
        //请求放行时，封装的是上一步创建的ServerHttpRequest对象
        return DataBufferUtils.join(serverHttpRequest.getBody())
                .flatMap(dataBuffer -> {
                    //处理dataBuffer时，不能被释放
                    DataBufferUtils.retain(dataBuffer);
                    //封装的请求体的副本
                    Flux<DataBuffer> flux=Flux.defer(()->{
                        return Flux.just(dataBuffer.slice(0,dataBuffer.readableByteCount()));
                    });
                    //请求体的副本创建新的serverHttpRequest2对象
                    ServerHttpRequest serverHttpRequest2=new ServerHttpRequestDecorator(serverHttpRequest){
                        @Override
                        public Flux<DataBuffer> getBody() {
                            return flux;
                        }
                    };
                    return chain.filter(exchange.mutate().request(serverHttpRequest2).build());
                });
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
